﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace AnaViewer
{
    /// <summary>
    /// 图像处理类
    /// </summary>
    public static class ImageProcesser
    {
        public static Bitmap ToGray(Image image)
        {
            if(image == null)
                return null;

            Bitmap bmp = new Bitmap(image.Width, image.Height);
            using( Graphics g = Graphics.FromImage(bmp))
                g.DrawImage(image,new Rectangle(0,0,bmp.Width,bmp.Height),new Rectangle(0,0,image.Width,image.Height), GraphicsUnit.Pixel);

            return ToGray(bmp, 0);
        }


        /// <summary>
        /// 变成黑白图
        /// http://blog.csdn.net/ki1381/archive/2007/03/04/1520544.aspx
        /// </summary>
        /// <param name="bmp">原始图</param>
        /// <param name="mode">模式。0:加权平均  1:算数平均</param>
        /// <returns></returns>
        public static Bitmap ToGray(Bitmap bmp,int mode)
        {
            if (bmp == null)
            {
                return null;
            }

            int w = bmp.Width;
            int h = bmp.Height;
            try
            {
                byte newColor = 0;
                BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                unsafe
                {
                    byte* p = (byte*)srcData.Scan0.ToPointer();
                    for (int y = 0; y < h; y++)
                    {
                        for (int x = 0; x < w; x++)
                        {

                            if (mode == 0)　// 加权平均
                            {
                                newColor = (byte)((float)p[0] * 0.114f + (float)p[1] * 0.587f + (float)p[2] * 0.299f);
                            }
                            else　　　　// 算数平均
                            {
                                newColor = (byte)((float)(p[0] + p[1] + p[2]) / 3.0f);
                            }
                            p[0] = newColor;
                            p[1] = newColor;
                            p[2] = newColor;

                            p += 3;
                        }
                        p += srcData.Stride - w * 3;
                    }
                    bmp.UnlockBits(srcData);
                    return bmp;
                }
            }
            catch
            {
                return null;
            }

        }
    }

}
